import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import '../http/model/course_mo.dart';
import 'common_widget.dart';

class HiCourse extends StatelessWidget {
  final List<Course> list;

  const HiCourse({super.key, required this.list});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        buildTitle("职场进阶", "带你突破职场瓶颈"),
        const Padding(padding: EdgeInsets.only(top: 5)),
        ..._buildCourseCard(context, list),
        const Padding(padding: EdgeInsets.only(top: 5)),
      ],
    );
  }

  _buildCourseCard(BuildContext context, List<Course> courseList) {
    var map = <int, List<Course>>{};
    for (var e in courseList) {
      var group = e.group;
      if (map[group] == null) {
        map[group] = <Course>[];
      }
      map[group]!.add(e);
    }

    return map.entries.map((entry) {
      List<Course> list = entry.value;
      //根据卡片数量计算出每个卡片的宽度
      var width =
          (MediaQuery.of(context).size.width - 20 - (list.length - 1) * 5) /
              list.length;
      var height = width / 16 * 6;
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [...list.map((course) => _buildCourseImage(height, width, course.cover,onTap: (){
          launchUrl(Uri.parse(course.url));
        }))],
      );
    });
  }

  _buildCourseImage(
      double height,
      double width,
      String url,
      {VoidCallback? onTap}) {
    return Padding(
      padding: const EdgeInsets.only(top: 5, bottom: 5),
      child: InkWell(
        onTap: () {
          onTap?.call();
        },
        child: ClipRRect(
          borderRadius: const BorderRadius.all(Radius.circular(5)),
          child: Image.network(
            url,
            height: height,
            width: width,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }
}
